package org.opens.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtil {

    private static JedisPool jedisPool;

    /*
    //这个静态代码块是用来非spring boot项目下加载properties型的redis配置文件的.
    static {
        InputStream resourceAsStream = JedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    */

    public static Jedis getJedis() {
        if(jedisPool != null) {
            return jedisPool.getResource();
        }
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //设置最大连接数
        jedisPoolConfig.setMaxTotal(20);
        //设置最大空闲数量
        jedisPoolConfig.setMaxIdle(20);

        jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
        return jedisPool.getResource();
    }

    public static void close(Jedis jedis) {
        if(jedis != null) {
            jedis.close();
        }
    }

}
